<template>
    <div
        v-if="isExternal"
        :style="styleExternalIcon"
        class="svg-external-icon svg-icon"
        v-on="$listeners"
    ></div>
    <svg
        v-else
        :class="svgClass"
        aria-hidden="true"
        v-on="$listeners"
    >
        <use
            :fill="fillColor"
            :xlink:href="iconName"
        />
    </svg>
</template>

<script>
import { isExternal } from '@/utils/validate';

export default {
    name: 'SvgIcon',
    props: {
        iconClass: { // svg图标对应的名称
            type: String,
            required: true,
        },
        className: { // 自定义svg的类名
            type: String,
            default: '',
        },
        fillColor: { // 填充色
            type: String,
        },
    },
    computed: {
        isExternal() {
            return isExternal(this.iconClass);
        },
        iconName() {
            return `#icon-${this.iconClass}`;
        },
        svgClass() {
            return this.className ? 'svg-icon ' + this.className : 'svg-icon';
        },
        styleExternalIcon() {
            return {
                mask: `url(${this.iconClass}) no-repeat 50% 50%`,
                '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`,
            };
        },
    },
};
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover!important;
  display: inline-block;
}
</style>
